<?php

use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use App\Common\ApiErrorCode;

use function Termwind\render;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        // api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        then:function(){
            Route::middleware(['api','auth:api'])
                ->prefix('api')
                ->name('api.')
                ->group(base_path('routes/api.php'));

            Route::middleware(['api','auth:admin'])
                ->prefix('api-admin')
                ->name('api-admin.')
                ->group(base_path('routes/admin.php'));
        }
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->redirectGuestsTo(fn(Request $request) => response());
        $middleware->alias([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //单个实例的异常只被报告一次
        $exceptions->dontReportDuplicates();
        //将异常渲染为json响应
        $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
            if ($request->is('api-admin/*') || $request->is('api/*')) {
                return true;
            }
            return $request->expectsJson();
        });

        $exceptions->render(function (\Spatie\Permission\Exceptions\UnauthorizedException $e, $request) {
            return response()->json( [
                'code' => 403,
                'msg' => '无此权限',
                'data' => null
            ]);
        });

        // $exceptions->respond(function (Response $response){
        //     if ($response->getStatusCode() === 401) {
        //         return response()->json([
        //             'code' => 401,
        //             'msg' => 'Unauthorized',
        //             'data' => null
        //         ]);
        //     }
        //     return $response;
        // });

        // //验证异常（表单）
        $exceptions->render(function (ValidationException $e) {
            $errors = $e->errors();
            // 提取第一个错误的提示信息（数组结构：['字段名' => ['错误信息']]）
            $firstError = '';
            if (!empty($errors)) {
                $firstFieldErrors = reset($errors); // 获取第一个字段的错误数组
                $firstError = reset($firstFieldErrors); // 获取该字段的第一个错误
            }
            return response()->json( [
                'code' => 422,
//                'msg' => $e->getMessage(),
                'msg' => $firstError,
                'data' => null
            ]);
        });

        /**
         * 认证异常
         */
        $exceptions->render(function (AuthenticationException $e){
            return apiResponseError(ApiErrorCode::UNAUTHORIZED);
        });

        /**
         * 模型未找到异常
         */
        $exceptions->render(function (NotFoundHttpException $e){
            $previousException = $e->getPrevious();
            if($previousException instanceof ModelNotFoundException){
                return response()->json( [
                    'code' => 4003,
                    'msg' => 'model not found',
                    'data' => null
                ]);
            }
        });

    })->create();
